'use strict'

const _ = require('underscore')
const Promise = require('bluebird')
const AV = require('leanengine')
const utils = require('../libs/utils')
const RtUtils = require('../libs/realtimeUtils')
const rp = require('request-promise')

const func = {

  queueUp (req) {
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId
    const stage = req.params.stage
    const courtIndex = req.params.courtIndex
    const matchSettings = req.params.matchSettings
    const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}`

    return rp(uri + '.json')
    .then(ret => {
      ret = JSON.parse(ret)
      var state = ret.state
      var _uri
      // if (state !== 'playing') return
      if (stage.stage === 'groups') {
        if (ret.groups[stage.groupIndex].matches[stage.matchIndex].state !== 'preparing') {
          return Promise.reject()
        }
        _uri = uri + `/groups/${stage.groupIndex}/matches/${stage.matchIndex}`
      } else if (stage.stage === 'playoffs') {
        if (ret.playoffs[stage.roundIndex].matches[stage.matchIndex].state !== 'preparing') {
          return Promise.reject()
        }
        _uri = uri + `/playoffs/${stage.roundIndex}/matches/${stage.matchIndex}`
      }

      var promises = [
        rp({
          uri: _uri + '/state.json',
          method: 'PUT',
          body: 'upcoming'
        }),
        rp({
          uri: uri + '/queue.json',
          method: 'POST',
          body: JSON.stringify({
            stage,
            state: 'upcoming',
            createdAt: new Date().toISOString(),
            matchSettings,
            courtIndex
          })
        })
      ]
      return Promise.all(promises).then(ret => {
        return rp({
          uri: _uri + '/queueKey.json',
          method: 'PUT',
          body: JSON.parse(ret[1]).name
        })
      })
    })
  },

  updateQueue (req) {
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId
    const courtIndex = req.params.courtIndex
    const matchSettings = req.params.matchSettings
    const key = req.params.key
    const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}`

    return rp({
      method: 'PATCH',
      uri: uri + `/queue/${key}.json`,
      body: JSON.stringify({
        updatedAt: new Date().toISOString(),
        courtIndex,
        matchSettings
      })
    })
  },

  saveSubTournamentOrder (req) {
    const order = req.params.order
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId
    const discipline = req.params.discipline
    var groups = order.map(el => {
      return {
        teams: el.map(el => {
          return {
            objectId: el
          }
        }),
        matches: utils.genGroupMatches(el)
      }
    })
    return rp({
      method: 'PUT',
      uri: `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}.json`,
      body: JSON.stringify({
        groups,
        state: 'orderReleased',
        discipline,
        courts: [
          {
            name: '3',
            umpire: '575251faa341310063bf7e22'
          }, {
            name: '4',
            umpire: '578b40bf6be3ff006cdad161'
          }
        ],
        createdAt: new Date().toISOString()
      })
    })
  },

  savePlayoffs (req) {
    const order = req.params.order
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId
    const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}/playoffs.json`
    return rp({
      method: 'PUT',
      uri,
      body: JSON.stringify([{
        round: order.length * 2,
        matches: order.map(el => {
          return {
            scores: [0, 0],
            teams: el.map(el => {
              return {objectId: el}
            }),
            state: 'preparing'
          }
        })
      }])
    })
  },

  matchStart (req) {
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId
    const key = req.params.key

    const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}/queue/${key}.json`
    return rp({
      uri,
      method: 'PATCH',
      body: JSON.stringify({
        state: 'ongoing'
      })
    })
  },

  revertSnapshot (req) {
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId
    const queueKey = req.params.queueKey
    const lastSnapshot = req.params.lastSnapshot
    const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}/queue/${queueKey}`

    return rp({
      uri: uri + '/lastSnapshot.json',
      method: 'PUT',
      body: JSON.stringify(lastSnapshot)
    })
  },

  getSubTournament (req) {
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId
    const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}.json`
    return rp(uri).then(ret => {
      return Promise.resolve(JSON.parse(ret))
    })
  },

  getSubTournamentGroups (req) {
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId
    const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}/groups.json`
    return rp(uri).then(ret => {
      return Promise.resolve(JSON.parse(ret))
    })
  },

  getQueue (req) {
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId
    const queueKey = req.params.queueKey

    const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}/queue/${queueKey}`

    // var promises = [
    //   rp(uri + '/snapshot.json?orderBy="$key"&limitToLast=1'),
    //   rp(uri + '.json?orderBy="$key"')
    // ]

    return rp(uri + '.json')
    .then(ret => {
      return Promise.resolve(JSON.parse(ret))
    })
  },

  getCourts (req) {
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId

    const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}/courts.json`

    return rp(uri).then(ret => Promise.resolve(JSON.parse(ret)))
  },

  saveCourts (req) {
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId
    const courts = req.params.courts

    const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}/courts.json`

    return rp({
      method: 'PUT',
      uri,
      body: JSON.stringify(courts)
    })
  },

  matchComplete (req) {
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId
    const queueKey = req.params.queueKey
    const stage = req.params.stage
    const lastSnapshot = req.params.lastSnapshot
    const winnerIndex = lastSnapshot.winnerIndex
    const loserIndex = winnerIndex === 1 ? 0 : 1
    const withdrawalIndex = lastSnapshot.withdrawalIndex

    const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}`

    var _uri

    return rp({
      method: 'PUT',
      uri: uri + `/queue/${queueKey}/state.json`,
      body: 'completed'
    }).then(() => {
      if (stage.stage === 'groups') {
        _uri = uri + `/groups/${stage.groupIndex}/matches/${stage.matchIndex}/state.json`
      } else if (stage.stage === 'playoffs') {
        _uri = uri + `/playoffs/${stage.roundIndex}/matches/${stage.matchIndex}/state.json`
      }
      return rp({
        method: 'PUT',
        uri: _uri,
        body: 'completed'
      })
    }).then(() => {
      if (stage.stage === 'groups') {
        console.log('winnerIndex', winnerIndex)
        var promises = [
          rp({
            uri: uri + `/groups/${stage.groupIndex}/teams/${stage.teamIndex[winnerIndex]}/scores/w.json`,
            method: 'POST',
            body: '1'
          }),
          rp({
            uri: uri + `/groups/${stage.groupIndex}/teams/${stage.teamIndex[loserIndex]}/scores/l.json`,
            method: 'POST',
            body: '1'
          })
        ]
        return Promise.all(promises).then(() => {
          var promises = [
            rp({
              uri: uri + `/groups/${stage.groupIndex}/winners.json`,
              method: 'POST',
              body: stage.teamIndex[winnerIndex] + ''
            }),
            rp({
              uri: uri + `/groups/${stage.groupIndex}/losers.json`,
              method: 'POST',
              body: stage.teamIndex[loserIndex] + ''
            })
          ]
          return Promise.all(promises)
          // return Promise.all(promises).then(() => {
          //   return this.genGroupMatch(req)
          // })
        })
      } else if (stage.stage === 'playoffs') {
        _uri = uri + `/playoffs/${stage.roundIndex}/matches/${stage.matchIndex}/state.json`
      }
    })
  },

  getLadder (req) {
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId
    const signUpObjId = req.params.signUpObjId

    const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}/ladderReady.json`

    return rp(uri)
    .then(ret => {
      ret = JSON.parse(ret)
      ret = _.map(ret, x => x)
      return Promise.resolve(ret.indexOf(signUpObjId) !== -1)
    })
  },

  ladderReady (req) {
    const tournamentObjId = req.params.tournamentObjId
    const subTournamentObjId = req.params.subTournamentObjId
    const signUpObjId = req.params.signUpObjId

    const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}/ladderReady.json`

    return rp(uri)
    .then(ret => {
      ret = JSON.parse(ret)
      ret = _.map(ret, x => x)
      if (ret.indexOf(signUpObjId) !== -1) {
        return Promise.reject({
          msg: 'is ready'
        })
      }
      return rp({
        uri,
        method: 'POST',
        body: signUpObjId
      })
    })
  }

  // genGroupMatch (req) {
  //   const tournamentObjId = req.params.tournamentObjId
  //   const subTournamentObjId = req.params.subTournamentObjId
  //   const stage = req.params.stage
  //
  //   const uri = `https://birdie2.wilddogio.com/tournaments/${tournamentObjId}/subTournaments/${subTournamentObjId}/groups/${stage.groupIndex}`
  //   return rp(uri + '.json')
  //   .then(ret => {
  //     ret = JSON.parse(ret)
  //     const wSize = _.size(ret.winners)
  //     const lSize = _.size(ret.losers)
  //     const nextMatchIndex = ret.matches.length
  //     const winners = _.map(ret.winners, x => x)
  //     const losers = _.map(ret.losers, x => x)
  //     var nextMatch
  //     switch (wSize) {
  //       case 2:
  //         nextMatch = {
  //           [nextMatchIndex]: {
  //             state: 'preparing',
  //             teams: winners.map(teamIndex => {
  //               return {objectId: ret.teams[teamIndex].objectId}
  //             })
  //           },
  //           [nextMatchIndex + 1]: {
  //             state: 'preparing',
  //             teams: losers.map(teamIndex => {
  //               return {objectId: ret.teams[teamIndex].objectId}
  //             })
  //           }
  //         }
  //         break
  //       case 4:
  //         nextMatch = {
  //           [nextMatchIndex]: {
  //             state: 'preparing',
  //             teams: _.intersection(winners, losers).map(teamIndex => {
  //               return {objectId: ret.teams[teamIndex].objectId}
  //             })
  //           }
  //         }
  //         break
  //     }
  //     if (nextMatch)
  //       return rp({
  //         method: 'PATCH',
  //         uri: uri + '/matches.json',
  //         body: JSON.stringify(nextMatch)
  //       })
  //     else {
  //       return Promise.resolve()
  //     }
  //   })
  // }
}

AV.Cloud.define('tournamentRealtime', function (req, res) {
  var promise
  if (!req.user) {
    promise = Promise.reject({
      msg: 'not loged in'
    })
  } else {
    promise = func[req.params.method](req)
  }
  return promise.then(function (ret) {
    res.success(ret)
  }).catch(function (err) {
    console.log(err)
    res.error(err)
  })
})
